package service

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"choujiang/common/consts"
	"choujiang/common/db"
	"choujiang/common/models"
	"choujiang/common/utils"
	"choujiang/common/variable"
	"net/http"
	"net/url"
	"strconv"
	"time"
)

type ResQrcode struct {
	Status   int64  `json:"status"`
	Filename string `json:"filename"`
}

/**
 获取用户的分享二维码地址
 */
func GetUserQrscene(user *model.User, gameId string, poster *model.Poster, page string, goodsId int64, cover string) (string, *utils.ErrorType) {
	boxEntry := variable.EntryBoxs[gameId]
	backgroundImg := ""
	uChannel := ""
	if user.FromChannel != "" {
		uChannel = user.FromChannel
	} else {
		uChannel = "leyouguanfang"
	}
	go func() {
		db.Mgo.UpdateScene(uChannel, user.Id, poster.Id, goodsId)
	}()
	channel := strconv.FormatInt(poster.Id, 10) + "_" + uChannel + "_" + strconv.FormatInt(user.Id, 10) + "_" + strconv.FormatInt(goodsId, 10)
	cmd := db.MainRedisClient.Exists(channel)
	if cmd.Val() == 1 { //缓存内有数据
		str := db.MainRedisClient.Get(channel)
		backgroundImg = str.Val()
	} else { //缓存内没数据
		val, b := db.Mgo.GetChannelBackground(channel)
		if !b { //mgo内没有记录，去生成
			resp, err := http.PostForm("https://mp.leyougame.cc/wechat/goods_qr",
				url.Values{"scene": {channel}, "nickname": {user.NickName}, "headimg": {user.HeadImgUrl}, "app_id": {boxEntry.AppId}, "app_secret": {boxEntry.AppSecret}, "goods_cover": {cover}, "page": {page}})
			if err != nil {
				err = fmt.Errorf("[GetUserQrscene]failed, err: %+v\n", err)
				fmt.Printf("[GetUserQrscene]failed, err: %+v\n", err)
				return "", consts.ErrInterval
			}
			defer resp.Body.Close()
			if resp.StatusCode != http.StatusOK {
				err = fmt.Errorf("[GetUserQrscene]failed, http.Status: %s", resp.Status)
				fmt.Printf("[GetUserQrscene]failed, http.Status: %s", resp.Status)
				return "", consts.ErrInterval
			}
			body, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				err = fmt.Errorf("[GetUserQrscene]failed, err: %+v\n", err)
				fmt.Printf("[GetUserQrscene]failed, err: %+v\n", err)
				return "", consts.ErrInterval
			}
			resRr := new(ResQrcode)
			if err = json.Unmarshal(body, resRr); err != nil {
				err = fmt.Errorf("[CodeToUserInfo]failed to parse json failed: %s, err :%+v\n", string(body), err)
				fmt.Printf("[GetUserQrscene]failed, err: %+v\n", err)
				return "", consts.ErrInterval
			}
			backgroundImg = resRr.Filename
			fmt.Printf("------------backgroundImg: %s", backgroundImg)
			go func() {
				//mgo记录渠道背景图关联关系
				db.Mgo.UpdChannelBackground(channel, resRr.Filename)
				//内存缓存
				db.MainRedisClient.Set(channel, resRr.Filename, time.Hour*2)
			}()
		} else { //mgo内有数据，更新缓存
			db.MainRedisClient.Set(channel, val, time.Hour*2)
			backgroundImg = val
		}
	}
	return backgroundImg, nil
}
